//
//  StoreDataAnalyseViewController.m
//  Manager
//
//  Created by Mr.Lee on 2018/4/18.
//  Copyright © 2018年 Reabam. All rights reserved.
//

#import "StoreDataAnalyseViewController.h"
#import "StoreDataHeaderView.h"
#import "SellConditionDetialController.h"
#import "MJRefresh.h"
#import "TSFooterRefresh.h"                 // 刷新
#import "TSHeaderRefresh.h"
#import "CommercialModel.h"
#import "StoreDataCell.h"
#import "FilterView.h"
#import "ManagerSheetView.h"
#import "TitleHeaderView.h"
#import "AAChartKit.h"
#define K_CellHeight 200

@interface StoreDataAnalyseViewController ()<StoreDataHeaderViewDelegate, UITableViewDelegate, UITableViewDataSource, FilterViewDelegate, ManagerSheetViewDelegate, AAChartViewDidFinishLoadDelegate, titleHeaderViewDelegate>
{
    UITableView *table;
    NSString *_orderSort;
//    UIView *tableHeaderView;
    UIButton *sat;
    UIButton *sat1; // 客单数
    UIButton *btnNormal;
    UIButton *sat2; // 平均客单数
    UIButton *btnNormal2;
    UIButton *sat3; // 销售额
    UIButton *btnNormal3;
    BOOL saveAccount;
    ManagerSheetView *bottomView;
    
    int pageNumber;
    NSString *pageSize;
    NSString *result;
    NSString*TotalCount;
    UIView*noDataView;
    UIView*noDataView1;
    UIView*noDataView2;
    UIView*noDataView3;
    NSMutableArray*modelArray;
    
    // 筛选
    NSString *orderField;
    NSMutableArray*searchBeans;
    NSMutableArray*allDataArray;

    // 统计图
//    UIImageView *lineIV;
    UIScrollView *_monitorScrollView;
    
    BOOL isSelected;
   
}
//@property (nonatomic, weak) StoreDataHeaderView *titleHeader;

@property (nonatomic, weak) TitleHeaderView *topTitleView;
@property (nonatomic, weak) StoreDataHeaderView *headerTopV;


@property (nonatomic, strong) NSString *sats;
@property (nonatomic, strong) NSString *orderCountTotal; // 订单总数
//@property (nonatomic, strong) NSString *salesTotal;  // 销售总额
@end

@implementation StoreDataAnalyseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"门店客单分析";
    searchBeans = [NSMutableArray array];
    modelArray = [NSMutableArray array];
    isSelected = YES;
    orderField = @"amount";
    _orderSort = @"desc";
    pageSize = @"20";
    // 设置筛选按钮
    UIImage *img=[UIImage imageNamed:@"shaixuan"];
    UIImage *tinted = [img rt_tintedImageWithColor:[UIColor whiteColor]];
    UIButton*shaixuan = [[UIButton alloc] initWithFrame:CGRectMake(30, 0.0, 60/2, 60/2)];
    [shaixuan setImage:tinted forState:UIControlStateNormal];
    [shaixuan addTarget:self action:@selector(searchBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* myBtnBtn = [[UIBarButtonItem alloc] initWithCustomView:shaixuan];
    self.navigationItem.rightBarButtonItem = myBtnBtn;

    // header
    TitleHeaderView *topTitleView = [TitleHeaderView titleHeaderViewWithNib];
    topTitleView.frame = CGRectMake(0, 0, ScreenWidth, 40);
    topTitleView.delegate = self;
    self.topTitleView = topTitleView;
    [self.view addSubview:topTitleView];
//    StoreDataHeaderView *header = [StoreDataHeaderView storeDataHeaderViewWithNib];
//    header.delegate = self;
//    self.titleHeader = header;
//    header.frame = CGRectMake(0, 0, ScreenWidth, 140);
//    [self.view addSubview:header];
    
    // 设置HeaderView
//    [self tableHeaderView];
    // tableView
    [self addTable];
    // 集成刷新控件
    [self setUpRefresh];
    // 数据请求
    [self requestData];
}


- (void)searchBtnClick:(UIButton *)sender{
    
    [bottomView hide];
    
    FilterView *filterView=[FilterView FilterViewWithSize:CGSizeMake(ScreenWidth, ScreenHeight)];
    filterView.typeStr=@"storeGuest";
    filterView.delegate=self;
    filterView.allDataArray = allDataArray;
    [filterView show];
    
}
#pragma mark FilterViewDelegate
- (void)confirmFilter:(NSMutableArray *)searchBeansArray andAllData:(NSMutableArray *)array{
    searchBeans=searchBeansArray;
    allDataArray = [NSMutableArray array];
    allDataArray = array;
    [self requestData];
}

-(void)tableHeaderView{
//    tableHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, self.titleHeader.bottom, ScreenWidth,40)];
//    tableHeaderView.backgroundColor= [UIColor colorWithHexString:@"f8f8f8"];
//    [self.view addSubview:tableHeaderView];
//
//    // 商品
//    sat=[[UIButton alloc]initWithFrame:CGRectMake(15, 0, ScreenWidth/4, 40)];
//    [sat setTitle:@"门店名称" forState:UIControlStateNormal];
//    [sat setTitleColor:[UIColor colorWithHexString:@"141e34"] forState:UIControlStateNormal];
//    sat.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
//    sat.titleLabel.font=[UIFont systemFontOfSize:13];
//    [tableHeaderView addSubview:sat];
//
//    sat1=[[UIButton alloc]initWithFrame:CGRectMake(sat.right, 0, ScreenWidth/4-5, 40)];
//    [sat1 setTitle:@"客单数" forState:UIControlStateNormal];
//    [sat1 setTitleColor:[UIColor colorWithHexString:@"141e34"] forState:UIControlStateNormal];
//    sat1.titleLabel.font=[UIFont systemFontOfSize:13];
//    [sat1 addTarget:self action:@selector(sat1:) forControlEvents:UIControlEventTouchUpInside];
//    [sat1 setImage:[UIImage imageNamed:@"jiantou_normal"] forState:UIControlStateNormal];
//    [sat1 setTitleEdgeInsets:UIEdgeInsetsMake(0, -sat1.imageView.size.width, 0, sat1.imageView.size.width)];
//    [sat1 setImageEdgeInsets:UIEdgeInsetsMake(0, sat1.titleLabel.bounds.size.width, 0, -sat1.titleLabel.bounds.size.width)];
//    [tableHeaderView addSubview:sat1];
//
//
//    //客单价
//    sat2=[[UIButton alloc]initWithFrame:CGRectMake(sat1.right, 0, ScreenWidth/4-5, 40)];
//    [sat2 setTitle:@"客单价" forState:UIControlStateNormal];
//    [sat2 setTitleColor:[UIColor colorWithHexString:@"141e34"] forState:UIControlStateNormal];
//    sat2.titleLabel.font=[UIFont systemFontOfSize:13];
//    [sat2 addTarget:self action:@selector(sat2:) forControlEvents:UIControlEventTouchUpInside];
//    [sat2 setImage:[UIImage imageNamed:@"jiantou_normal"] forState:UIControlStateNormal];
//    [sat2 setTitleEdgeInsets:UIEdgeInsetsMake(0, -sat2.imageView.size.width, 0, sat2.imageView.size.width)];
//    [sat2 setImageEdgeInsets:UIEdgeInsetsMake(0, sat2.titleLabel.bounds.size.width, 0, -sat2.titleLabel.bounds.size.width)];
//    [tableHeaderView addSubview:sat2];
//
//
//    //销售额
//    sat3=[[UIButton alloc]initWithFrame:CGRectMake(sat2.right, 0, ScreenWidth/4-5, 40)];
//    [sat3 setTitle:@"销售额" forState:UIControlStateNormal];
//    [sat3 setTitleColor:[UIColor colorWithHexString:@"141e34"] forState:UIControlStateNormal];
//    sat3.titleLabel.font=[UIFont systemFontOfSize:13];
//    [sat3 addTarget:self action:@selector(sat3:) forControlEvents:UIControlEventTouchUpInside];
//    [sat3 setImage:[UIImage imageNamed:@"xia_hight"] forState:UIControlStateNormal];
//    [sat3 setTitleEdgeInsets:UIEdgeInsetsMake(0, -sat3.imageView.size.width, 0, sat3.imageView.size.width)];
//    [sat3 setImageEdgeInsets:UIEdgeInsetsMake(0, sat3.titleLabel.bounds.size.width, 0, -sat3.titleLabel.bounds.size.width)];
//    [tableHeaderView addSubview:sat3];
//
//    saveAccount = NO;
}



// 客单数
-(void)sat1:(UIButton*)sender{
    saveAccount=!saveAccount;
    orderField = @"quantity";
    if (saveAccount) {
        _orderSort=@"asc";
        [sat1 setImage:[UIImage imageNamed:@"shang_hight"] forState:UIControlStateNormal];
//        [sat1 setTitle:@"客单数" forState:UIControlStateNormal];
    }else{
        _orderSort=@"desc";
        [sat1 setImage:[UIImage imageNamed:@"xia_hight"] forState:UIControlStateNormal];
//        [sat1 setTitle:@"客单数" forState:UIControlStateNormal];
    }
    
    [sat2 setImage:[UIImage imageNamed:@"jiantou_normal"] forState:UIControlStateNormal];
//    [sat2 setTitle:@"客单价" forState:UIControlStateNormal];
    
    [sat3 setImage:[UIImage imageNamed:@"jiantou_normal"] forState:UIControlStateNormal];
//    [sat3 setTitle:@"销售额" forState:UIControlStateNormal];
    
    [self requestData];
}
// 客单价
-(void)sat2:(UIButton*)sender{
    saveAccount=!saveAccount;
    orderField = @"guestOPrice";
    if (saveAccount) {
        _orderSort=@"asc";
        [sat2 setImage:[UIImage imageNamed:@"shang_hight"] forState:UIControlStateNormal];
    }else{
        _orderSort=@"desc";
        [sat2 setImage:[UIImage imageNamed:@"xia_hight"] forState:UIControlStateNormal];
    }
    
    [sat1 setImage:[UIImage imageNamed:@"jiantou_normal"] forState:UIControlStateNormal];
    [sat3 setImage:[UIImage imageNamed:@"jiantou_normal"] forState:UIControlStateNormal];
    
    [self requestData];
}


// 销售额
-(void)sat3:(UIButton*)sender{
    saveAccount=!saveAccount;
    orderField = @"amount";
    if (saveAccount) {
        _orderSort=@"asc";
        [sat3 setImage:[UIImage imageNamed:@"shang_hight"] forState:UIControlStateNormal];
    }else{
        _orderSort=@"desc";
        [sat3 setImage:[UIImage imageNamed:@"xia_hight"] forState:UIControlStateNormal];
    }
    [sat1 setImage:[UIImage imageNamed:@"jiantou_normal"] forState:UIControlStateNormal];
    [sat2 setImage:[UIImage imageNamed:@"jiantou_normal"] forState:UIControlStateNormal];
    [self requestData];
}

-(void)addTable{
    
    [table removeFromSuperview];
//    table = [[UITableView alloc]initWithFrame:CGRectMake(0,tableHeaderView.bottom, ScreenWidth, ScreenHeight-self.titleHeader.height-64- tableHeaderView.height) style:UITableViewStylePlain];
    table = [[UITableView alloc]initWithFrame:CGRectMake(0,40, ScreenWidth, ScreenHeight-40-64) style:UITableViewStylePlain];
    
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    table.delegate=self;
    table.dataSource=self;
    [self.view addSubview:table];
    
    
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, ScreenWidth, 140);
    headerView.backgroundColor = [UIColor whiteColor];
    table.tableHeaderView = headerView;
    
    
    //    SellConditionHeaderView *header = [SellConditionHeaderView sellConditionHeaderViewWithNib];
    //    header.delegate = self;
    //    self.titleHeader = header;
    //    header.frame = CGRectMake(0, 0, ScreenWidth, 140);
    
//    StoreDataHeaderView *header = [StoreDataHeaderView storeDataHeaderViewWithNib];
//    header.delegate = self;
//    self.titleHeader = header;
//    header.frame = CGRectMake(0, 0, ScreenWidth, 140);
//    [self.view addSubview:header];
    
    StoreDataHeaderView *headerTopV = [StoreDataHeaderView storeDataHeaderViewWithNib];
    headerTopV.delegate = self;
    self.headerTopV = headerTopV;
    //    headerTopV.leftStr.text = @"订单总数";
    headerTopV.frame = CGRectMake(0, 0, ScreenWidth, 100);
    [headerView addSubview:headerTopV];
    
    UIView *headerBottomV =[[UIView alloc]initWithFrame:CGRectMake(0, headerTopV.bottom, ScreenWidth,40)];
    headerBottomV.backgroundColor= [UIColor colorWithHexString:@"f8f8f8"];
    [headerView addSubview:headerBottomV];
    
    
    // 商品
    sat=[[UIButton alloc]initWithFrame:CGRectMake(15, 0, ScreenWidth/4, 40)];
    [sat setTitle:@"门店名称" forState:UIControlStateNormal];
    [sat setTitleColor:[UIColor colorWithHexString:@"141e34"] forState:UIControlStateNormal];
    sat.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
    sat.titleLabel.font=[UIFont systemFontOfSize:13];
    [headerBottomV addSubview:sat];
    
    sat1=[[UIButton alloc]initWithFrame:CGRectMake(sat.right, 0, ScreenWidth/4-5, 40)];
    [sat1 setTitle:@"客单数" forState:UIControlStateNormal];
    [sat1 setTitleColor:[UIColor colorWithHexString:@"141e34"] forState:UIControlStateNormal];
    sat1.titleLabel.font=[UIFont systemFontOfSize:13];
    [sat1 addTarget:self action:@selector(sat1:) forControlEvents:UIControlEventTouchUpInside];
    [sat1 setImage:[UIImage imageNamed:@"jiantou_normal"] forState:UIControlStateNormal];
    [sat1 setTitleEdgeInsets:UIEdgeInsetsMake(0, -sat1.imageView.size.width, 0, sat1.imageView.size.width)];
    [sat1 setImageEdgeInsets:UIEdgeInsetsMake(0, sat1.titleLabel.bounds.size.width, 0, -sat1.titleLabel.bounds.size.width)];
    [headerBottomV addSubview:sat1];
    
    
    //客单价
    sat2=[[UIButton alloc]initWithFrame:CGRectMake(sat1.right, 0, ScreenWidth/4-5, 40)];
    [sat2 setTitle:@"客单价" forState:UIControlStateNormal];
    [sat2 setTitleColor:[UIColor colorWithHexString:@"141e34"] forState:UIControlStateNormal];
    sat2.titleLabel.font=[UIFont systemFontOfSize:13];
    [sat2 addTarget:self action:@selector(sat2:) forControlEvents:UIControlEventTouchUpInside];
    [sat2 setImage:[UIImage imageNamed:@"jiantou_normal"] forState:UIControlStateNormal];
    [sat2 setTitleEdgeInsets:UIEdgeInsetsMake(0, -sat2.imageView.size.width, 0, sat2.imageView.size.width)];
    [sat2 setImageEdgeInsets:UIEdgeInsetsMake(0, sat2.titleLabel.bounds.size.width, 0, -sat2.titleLabel.bounds.size.width)];
    [headerBottomV addSubview:sat2];
    
    
    //销售额
    sat3=[[UIButton alloc]initWithFrame:CGRectMake(sat2.right, 0, ScreenWidth/4-5, 40)];
    [sat3 setTitle:@"销售额" forState:UIControlStateNormal];
    [sat3 setTitleColor:[UIColor colorWithHexString:@"141e34"] forState:UIControlStateNormal];
    sat3.titleLabel.font=[UIFont systemFontOfSize:13];
    [sat3 addTarget:self action:@selector(sat3:) forControlEvents:UIControlEventTouchUpInside];
    [sat3 setImage:[UIImage imageNamed:@"xia_hight"] forState:UIControlStateNormal];
    [sat3 setTitleEdgeInsets:UIEdgeInsetsMake(0, -sat3.imageView.size.width, 0, sat3.imageView.size.width)];
    [sat3 setImageEdgeInsets:UIEdgeInsetsMake(0, sat3.titleLabel.bounds.size.width, 0, -sat3.titleLabel.bounds.size.width)];
    [headerBottomV addSubview:sat3];
    
    saveAccount = NO;
    
}
// tubiao
-(void)addChartTable{
    
    [table removeFromSuperview];
    
//    lineIV = [[UIImageView alloc] init];
//    lineIV.frame = CGRectMake(10, self.titleHeader.bottom, ScreenWidth-20, 0.5);
//    lineIV.image = [UIImage imageNamed:@"hengxian"];
//    [self.view addSubview:lineIV];
    
//    table = [[UITableView alloc]initWithFrame:CGRectMake(0,40, ScreenWidth, ScreenHeight-self.titleHeader.height-64) style:UITableViewStyleGrouped];
    
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, self.topTitleView.bottom, ScreenWidth, ScreenHeight-40-64) style:UITableViewStyleGrouped];
    
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    table.backgroundColor =[UIColor whiteColor];
    table.delegate=self;
    table.tag = 20001;
    table.dataSource=self;
    [self.view addSubview:table];
    
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, ScreenWidth, 100);
    headerView.backgroundColor = [UIColor whiteColor];
    table.tableHeaderView = headerView;
    
    
    //    SellConditionHeaderView *header = [SellConditionHeaderView sellConditionHeaderViewWithNib];
    //    header.delegate = self;
    //    self.titleHeader = header;
    //    header.frame = CGRectMake(0, 0, ScreenWidth, 140);
    
    //    StoreDataHeaderView *header = [StoreDataHeaderView storeDataHeaderViewWithNib];
    //    header.delegate = self;
    //    self.titleHeader = header;
    //    header.frame = CGRectMake(0, 0, ScreenWidth, 140);
    //    [self.view addSubview:header];
    
    StoreDataHeaderView *headerTopV = [StoreDataHeaderView storeDataHeaderViewWithNib];
    headerTopV.delegate = self;
    self.headerTopV = headerTopV;
    //    headerTopV.leftStr.text = @"订单总数";
    headerTopV.frame = CGRectMake(0, 0, ScreenWidth, 100);
    [headerView addSubview:headerTopV];
    
}

// 刷新
- (void)setUpRefresh {
    
    table.mj_footer = [TSFooterRefresh footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreProductList)];
}


-(void)requestData{
    pageNumber=1;
    [noDataView removeFromSuperview];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"1" forKey:@"pageIndex"];
    [param setValue:pageSize forKey:@"pageSize"];
    //    排序字段 orderCount按单数 amount按金额
    [param setValue:orderField forKey:@"orderField"];
    //    排序方式 asc升序 desc降序
    [param setValue:_orderSort forKey:@"orderSort"];
    
    [param setValue:searchBeans forKey:@"searchBeans"];
    NSLog(@"%@", param);
    [MBProgressHUD showIndeterminateHudSub:@"" delay:30 view:self.view];
    [HttpRequest requestData:@"report/StoreGuest" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        NSLog(@"====%@",severDataDict.dataDict);
        if (isSuccess) {
            [modelArray removeAllObjects];
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [MBProgressHUD hideProgressHUDInternal:self.view];
                NSMutableArray* arrr=[[NSMutableArray alloc] init];
                arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                if (arrr.count == 0) {
                    noDataView=[[UIView alloc]initWithFrame:CGRectMake(0, (ScreenHeight-64-49)/2-50, ScreenWidth, 80)];
                    [self.view addSubview:noDataView];
                    UIImageView*noImage=[[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-47, 0, 94, 51)];
                    noImage.image=[UIImage imageNamed:@"meiyoushuju"];
                    [noDataView addSubview:noImage];
                    UILabel*noLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,65, ScreenWidth, 14)];
                    noLabel.text=@"没有列表数据！";
                    noLabel.textColor=zhonghuiColor; noLabel.font=[UIFont systemFontOfSize:14];
                    noLabel.textAlignment=NSTextAlignmentCenter;
                    [noDataView addSubview:noLabel];
                } else{
                    for (NSDictionary* dicc in arrr ) {
                        CommercialModel *model =[CommercialModel  mj_objectWithKeyValues:dicc];
                        [modelArray addObject:model];
                    }
                }
                [table reloadData];
               
                
                NSString *guestOQuantityTotal = [NSString stringWithFormat:@"%@",[severDataDict.dataDict objectForKey:@"guestOQuantityTotal"]];
                self.orderCountTotal = guestOQuantityTotal;
                
                NSString *guestOPriceTotal = [NSString stringWithFormat:@"%@",[severDataDict.dataDict objectForKey:@"guestOPriceTotal"]];
                NSString *saleAmountTotal = [NSString stringWithFormat:@"%@",[severDataDict.dataDict objectForKey:@"saleAmountTotal"]];
                
                NSString *beginDate = [NSString stringWithFormat:@"%@",[severDataDict.dataDict objectForKey:@"beginDate"]];
                NSString *endDate = [NSString stringWithFormat:@"%@",[severDataDict.dataDict objectForKey:@"endDate"]];
                
                if ([beginDate isEqualToString:endDate]) {
                    self.topTitleView.timeLabel.text = beginDate;
                } else{
                    self.topTitleView.timeLabel.text = [NSString stringWithFormat:@"%@~%@", beginDate, endDate];
                }
                
                // 总数
                self.headerTopV.totalCountLabel.text = [NSString stringWithFormat:@"%@", guestOQuantityTotal];
                
                // 平均数
                double pingjunshu = [guestOPriceTotal doubleValue];
                self.headerTopV.averageMoneyLabel.text= [NSString stringWithFormat:@"%.2f", pingjunshu];
                // 总金额
                double zongjine = [saleAmountTotal doubleValue];
                self.headerTopV.totalMoneyLabel.text = [NSString stringWithFormat:@"%.2f", zongjine];
                
                TotalCount= [NSString stringWithFormat:@"%@", [severDataDict.dataDict objectForKey:@"TotalCount"]];
                if (TotalCount.intValue < pageSize.intValue) {
                    [table.mj_footer endRefreshingWithNoMoreData];
                } else if(TotalCount.intValue >pageSize.intValue){
                    [table.mj_footer resetNoMoreData];
                }
            }else{
                [MBProgressHUD hideProgressHUDInternal:self.view];
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    LoginViewController *loginVC=[[LoginViewController alloc] init];//2.0{9个参数 少2个}
                    [self.navigationController pushViewController:loginVC animated:YES];
                }
                NSString *subStr = [severDataDict.dataDict objectForKey:@"ResultString"];
                [MBProgressHUD showTextHudSub:subStr view:self.view];
            }
            
        } else {
            [MBProgressHUD hideProgressHUDInternal:self.view];
            NSString *subStr = [severDataDict.dataDict objectForKey:@"ResultString"];
            [MBProgressHUD showTextHudSub:subStr view:self.view];
        }
        
    }];
    
}

// 上拉刷新
- (void)loadMoreProductList{
    if (TotalCount.floatValue/pageSize.floatValue > pageNumber) {
        pageNumber++;
        NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
        NSString* tokenId = [user1 objectForKey:@"tokenId"];
        NSMutableDictionary *params = [NSMutableDictionary new];
        [params setValue:tokenId forKey:@"tokenId"];
        [params setValue:[NSString stringWithFormat:@"%d" ,pageNumber] forKey:@"pageIndex"];
        [params setValue:pageSize forKey:@"pageSize"];
        [params setValue:orderField forKey:@"orderField"];
        [params setValue:_orderSort forKey:@"orderSort"];
        [params setValue:searchBeans forKey:@"searchBeans"];
        [MBProgressHUD showIndeterminateHudSub:@"" delay:30 view:self.view];
        [HttpRequest requestData:@"report/StoreGuest" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [MBProgressHUD hideProgressHUDInternal:self.view];
                    NSMutableArray* arrr=[[NSMutableArray alloc]init];
                    arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                    for (NSDictionary* dicc in arrr ) {
                        CommercialModel *model =[CommercialModel  mj_objectWithKeyValues:dicc];
                        [modelArray addObject:model];
                    }
                    [table reloadData];
                    TotalCount=[severDataDict.dataDict objectForKey:@"TotalCount"];
                    if (TotalCount.intValue < pageSize.intValue) {
                        [table.mj_footer endRefreshingWithNoMoreData];
                    } else if(TotalCount.intValue >pageSize.intValue){
                        [table.mj_footer resetNoMoreData];
                    }
                }else {
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
                }
                
            } else {
                [MBProgressHUD hideProgressHUDInternal:self.view];
                NSString *subStr = [severDataDict.dataDict objectForKey:@"ResultString"];
                [MBProgressHUD showTextHudSub:subStr view:self.view];
            }
            
        }];
    }else{
        NSString *requestResultStr=@"没有更多数据了！";
        [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
        [table.mj_footer endRefreshingWithNoMoreData];
        
    }
}




#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (tableView.tag ==20001) {
        return 2;
    } else{
        return 1;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView.tag == 20001) {
        return 1;
    } else{
        return modelArray.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView.tag ==20001) {
        
        [noDataView removeFromSuperview];
        
        static NSString *cellId = @"newcell";
        UITableViewCell *Cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (Cell == nil) {
            Cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
            Cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        for (id view in Cell.contentView.subviews) {
            [view removeFromSuperview];
        }
        
        
        NSMutableArray *companyNameArray = [NSMutableArray array];
        NSMutableArray *guestOPriceArray = [NSMutableArray array];
        NSMutableArray *guestOQuantityArray = [NSMutableArray array];
        
        for (CommercialModel *model in modelArray) {
//            [companyNameArray addObject:model.companyName];
            NSString *itemName = [NSString stringWithFormat:@"%@", model.companyName];
            if (itemName.length >=10) {
                itemName = [NSString stringWithFormat:@"%@...", [itemName substringToIndex:10]];
            }
            [companyNameArray addObject:itemName];
            
            NSString *totalAmount = [NSString stringWithFormat:@"%.2f", model.guestOPrice.doubleValue];
            NSNumber *numberT =[NSNumber numberWithDouble:[totalAmount doubleValue]];
            [guestOPriceArray addObject:numberT];
            
            NSString *orderCount = [NSString stringWithFormat:@"%@", model.guestOQuantity];
            NSNumber *numberT1 =[NSNumber numberWithInteger:orderCount.integerValue];
            [guestOQuantityArray addObject:numberT1];
        }
        
        //  柱状图
        if (indexPath.section == 0) {
            
            CGFloat KWidth = ScreenWidth;
            NSArray *categoriesArray = nil;
            NSArray *dataArray = nil;
            if (companyNameArray.count >= 50 && guestOPriceArray.count >= 50) {
                categoriesArray = [companyNameArray subarrayWithRange:NSMakeRange(0, 50)];
                dataArray = [guestOPriceArray subarrayWithRange:NSMakeRange(0, 50)];
            } else{
                categoriesArray = companyNameArray;
                dataArray = guestOPriceArray;
            }
            KWidth = 50*categoriesArray.count;
            if (KWidth <= 200) {
                KWidth = 200;
            }
            NSString *nameSet = @"客单价";
            
            NSNumber *sum = [dataArray valueForKeyPath:@"@sum.doubleValue"];
            NSString *sunStr = [NSString stringWithFormat:@"%@", sum.stringValue];
            if (sunStr.doubleValue == 0) {
                
//                UIImageView*iv = [[UIImageView alloc ] init];
//                iv.frame= CGRectMake(0, 0, ScreenWidth, K_CellHeight);
//                iv.contentMode = UIViewContentModeCenter;
//                iv.image = [UIImage imageNamed:@"meiyoushuju_tubiao01"];
//                [Cell.contentView addSubview:iv];
                noDataView1=[[UIView alloc]initWithFrame:CGRectMake(0, (K_CellHeight-80)/2, ScreenWidth, 80)];
                UIImageView*noImage=[[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-47, 0, 94, 51)];
                noImage.image=[UIImage imageNamed:@"meiyoushuju"];
                [noDataView1 addSubview:noImage];
                UILabel*noLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,65, ScreenWidth, 14)];
                noLabel.text=@"没有相关数据！";
                noLabel.textColor=zhonghuiColor; noLabel.font=[UIFont systemFontOfSize:14];
                noLabel.textAlignment=NSTextAlignmentCenter;
                [noDataView1 addSubview:noLabel];
                [Cell.contentView addSubview:noDataView1];
                
            } else{
                _monitorScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, K_CellHeight)];
                _monitorScrollView.bounces = NO;
                _monitorScrollView.contentSize = CGSizeMake(KWidth, 0);
                _monitorScrollView.showsHorizontalScrollIndicator = NO;
                _monitorScrollView.showsVerticalScrollIndicator = NO;
                [Cell.contentView addSubview:_monitorScrollView];
                
                AAChartView *aaChartView = [[AAChartView alloc]initWithFrame:CGRectMake(0, 0, KWidth, K_CellHeight)];
                aaChartView.userInteractionEnabled = YES;
                aaChartView.delegate = self;
                aaChartView.contentWidth = KWidth;
                aaChartView.scrollEnabled = NO;
                
                AAChartModel *aaChartModel = [self setUpCVWithNameSet:nameSet CategoriesArray:categoriesArray andDataArray:dataArray];
                [aaChartView aa_drawChartWithChartModel:aaChartModel];
                [_monitorScrollView addSubview:aaChartView];
            }
            
           
            
            // 圆形图
        } else if (indexPath.section == 1){
            
            AAChartView *chartView =[[AAChartView alloc]initWithFrame:CGRectMake(-5, 0, self.view.frame.size.width+5, K_CellHeight)];
            chartView.backgroundColor = [UIColor whiteColor];
            chartView.contentHeight = chartView.frame.size.height;
            chartView.userInteractionEnabled = YES;
            chartView.scrollEnabled = NO;
            
            NSString *seriesName = @"客单数";
            
            NSMutableArray *categoriesArray = [NSMutableArray array];
            NSMutableArray *dataArray = [NSMutableArray array];
            if (companyNameArray.count > 7 && guestOQuantityArray.count > 7) {
                categoriesArray =[NSMutableArray arrayWithArray:[companyNameArray subarrayWithRange:NSMakeRange(0, 7)]];
                dataArray = [NSMutableArray arrayWithArray:[guestOQuantityArray subarrayWithRange:NSMakeRange(0, 7)]];;
                
                NSNumber*sum = [dataArray valueForKeyPath:@"@sum.floatValue"];
                NSString *sumorder = [NSString stringWithFormat:@"%@",sum];
                
                NSString *otherNumStr = [NSString stringWithFormat:@"%ld", [self.orderCountTotal integerValue] - [sumorder integerValue]];
                NSString *other = @"其他";
                NSNumber *otherNum = [NSNumber numberWithInteger:otherNumStr.integerValue];
                [categoriesArray addObject:other];
                [dataArray addObject:otherNum];
                
            } else{
                categoriesArray = companyNameArray;
                dataArray = guestOQuantityArray;
            }
            
            NSMutableArray *allData = [NSMutableArray array];
            for (int i = 0 ; i < categoriesArray.count; i ++) {
                NSMutableArray *array = [NSMutableArray array];
                [array addObject:categoriesArray[i]];
                [array addObject:dataArray[i]];
                [allData addObject:array];
            }
            
            NSArray *dataArray1 = allData;
            
            NSArray *colorArray =@[@"#75c3f0", @"#79c4c6", @"#9ebc62", @"#cdc553", @"#f7bf6b", @"#f9a36a", @"#9b8dcd", @"#e27cac"];
            
            
            NSNumber *sum = [dataArray valueForKeyPath:@"@sum.doubleValue"];
            NSString *sunStr = [NSString stringWithFormat:@"%@", sum.stringValue];
            if (sunStr.doubleValue == 0) {
                
//                UIImageView*iv = [[UIImageView alloc ] init];
//                iv.frame= CGRectMake(0, 0, ScreenWidth, K_CellHeight);
//                iv.contentMode = UIViewContentModeCenter;
//                iv.image = [UIImage imageNamed:@"meiyoushuju_tubiao02"];
//                [Cell.contentView addSubview:iv];
                
                noDataView2=[[UIView alloc]initWithFrame:CGRectMake(0, (K_CellHeight-80)/2, ScreenWidth, 80)];
                UIImageView*noImage=[[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-47, 0, 94, 51)];
                noImage.image=[UIImage imageNamed:@"meiyoushuju"];
                [noDataView2 addSubview:noImage];
                UILabel*noLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,65, ScreenWidth, 14)];
                noLabel.text=@"没有相关数据！";
                noLabel.textColor=zhonghuiColor; noLabel.font=[UIFont systemFontOfSize:14];
                noLabel.textAlignment=NSTextAlignmentCenter;
                [noDataView2 addSubview:noLabel];
                [Cell.contentView addSubview:noDataView2];
                
            } else{
            
                AAOptions *chartOptions = [self configurePieWithSeriesName:seriesName DataArray:dataArray1 andColorArray:colorArray];
                [chartView aa_drawChartWithOptions:chartOptions];
                [Cell.contentView addSubview:chartView];
                
                UIButton *screnBtn = [[UIButton alloc] init];
                screnBtn.frame = CGRectMake(0, 0, 200, K_CellHeight);
                [screnBtn setBackgroundColor:[UIColor clearColor]];
                [Cell.contentView addSubview:screnBtn];
              
            }
        }
        return Cell;
        
    } else{
        CommercialModel *model = modelArray[indexPath.row];
        StoreDataCell *cell = [StoreDataCell storeDataCellFromXib:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.nameLabel.text = model.companyName;
        cell.countLabel.text = model.guestOQuantity;
        double guestOPrice = [model.guestOPrice doubleValue];
        cell.averagePriceLabel.text = [NSString stringWithFormat:@"%.2f", guestOPrice];;
        
        double saleAmount = [model.saleAmount doubleValue];
        cell.moneyLabel.text = [NSString stringWithFormat:@"%.2f", saleAmount];
        
        return cell;
    }
    
    
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 20001) {
        return 200;
    } else{
        return  54;
    }
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView.tag == 20001) {
        
    } else{
        
    }
//    CommercialModel *model = modelArray[indexPath.row];
//    SellConditionDetialController *vc = [[SellConditionDetialController alloc] init];
//    vc.title = model.companyName;
//    vc.companyId = model.companyId;
//    vc.view.backgroundColor = [UIColor whiteColor];
//    [self.navigationController pushViewController:vc animated:YES];
}
// 返回每行的header
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (tableView.tag ==20001) {
        
        UIView *headerView = [[UIView alloc] init];
        headerView.frame = CGRectMake(0, 0, ScreenWidth, 55);
        headerView.backgroundColor = [UIColor whiteColor];
        //        [self.view addSubview:headerView];
        
        UIView *lineView = [[UIView alloc] init];
        lineView.layer.borderColor = qianhuiColor.CGColor;
        lineView.layer.borderWidth = 0.5;
        lineView.frame = CGRectMake(0, 0, ScreenWidth, 10);
        lineView.backgroundColor = zuiqianhuiColor;
        [headerView addSubview:lineView];
        
        UIView *vw =[[UIView alloc] initWithFrame:CGRectMake(0, 10, ScreenWidth, 45)];
        [vw setBackgroundColor:[UIColor whiteColor]];
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.frame = CGRectMake(0, 10, ScreenWidth, 35);
        titleLabel.font = [UIFont systemFontOfSize:15.0];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.textColor = [UIColor colorWithHexString:@"333333"];
        [vw addSubview:titleLabel];
        
        if (section == 0) {
            titleLabel.text = @"客单价排名";
        } else if (section == 1){
            titleLabel.text = @"客单数占比";
        }
        [headerView addSubview:vw];
        
        
        return headerView;
        
        
    } else{
        UIView *vw =[[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.01)];
        [vw setBackgroundColor:[UIColor whiteColor]];
        return vw;
    }
    
}
// 返回每行的header高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView.tag == 20001) {
        return 55;
    } else{
        return 0.01;
    }
}

// 返回每行的Footer
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *vw =[[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.01)];
    [vw setBackgroundColor:[UIColor whiteColor]];
    return vw;
}
// 返回每行的Footer高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}


#pragma mark --
#pragma mark 图表框架
// 柱状图
- (AAChartModel *)setUpCVWithNameSet:(NSString *)nameSet CategoriesArray:(NSArray *)categoriesArray andDataArray:(NSArray *)dataArray{
    
    AAChartModel *aaChartModel= AAObject(AAChartModel)
    .chartTypeSet(AAChartTypeColumn)
    .titleSet(@"")
    .subtitleSet(@"")
    .colorsThemeSet(@[@"#92cff3"])//设置主体颜色数组
    .legendEnabledSet(false)//隐藏图例(底部可点按的小圆点)
    .categoriesSet(categoriesArray)
    .yAxisTitleSet(@"")
    .xAxisLabelsFontColorSet(@"#666666")
    //    .yAxisMaxSet(@150000)
    .seriesSet(@[
                 AAObject(AASeriesElement)
                 .nameSet(nameSet)
                 .dataSet(dataArray),
                 ]
               );
    return aaChartModel;
    
}


// 圆形图
- (AAOptions *)configurePieWithSeriesName:(NSString *)seriesName DataArray:(NSArray *)dataArray andColorArray:(NSArray *)colorArray{
    AAChart *aaChart = AAObject(AAChart)
    .typeSet(AAChartTypePie);
    //标题
    AATitle *aaTitle = AAObject(AATitle)
    .textSet(@"")//标题文本内容
    .alignSet(AAChartTitleAlignTypeCenter)//标题水平居中
    .verticalAlignSet(AAChartTitleVerticalAlignTypeTop)//标题垂直居中
    .styleSet(AAObject(AAStyle)
              .colorSet(@"#000000")//Title font color
              .fontSizeSet(@"14 px")//Title font size
              .fontWeightSet(@"bold")//Title font weight
              );
    
    AAPlotOptions *aaPlotOptions = (AAObject(AAPlotOptions)
                                    .seriesSet(AAObject(AASeries)
                                               .animationSet(AAObject(AAAnimation)
                                                             .easingSet(@"bounce")
                                                             .durationSet(@1000)
                                                             )
                                               )
                                    .pieSet(AAObject(AAPie)
                                            .showInLegendSet(true)
                                            .dataLabelsSet(AAObject(AADataLabels)
                                                           .enabledSet(true)
                                                           .styleSet(AAObject(AAStyle)
                                                                     .colorSet(@"#666666")
                                                                     )
                                                           .formatSet(@"{point.percentage:.1f}%"))
                                            )
                                    );
    
    //数据源
    NSArray *aaSeries = @[
                          AAObject(AASeriesElement)
                          .nameSet(seriesName)
                          .innerSizeSet(@"0%")//内部圆环半径大小占比
                          .allowPointSelectSet(false)//是否允许在点击数据点标记(扇形图点击选中的块发生位移)
                          .dataSet(dataArray),
                          ];
    
    NSArray *aaColors = colorArray;
    
    AALegend *legend = AAObject(AALegend)
    .enabledSet(true)
    //    .enabledSet(false)
    .verticalAlignSet(AALegendVerticalAlignTypeMiddle)
    .layoutSet(AALegendLayoutTypeVertical)
    .alignSet(AALegendAlignTypeLeft)
    .itemMarginTopSet(@4)
    .itemStyleSet(AAObject(AAItemStyle)
                  .colorSet(@"#666666")//Title font color
                  .fontSizeSet(@"12 px")//Title font size
                  .fontWeightSet(@"normal")//Title font weight
                  )
    ;
    
    AAOptions *chartOptions = AAObject(AAOptions);
    chartOptions.chart = aaChart;
    chartOptions.chart.backgroundColor = @"#ffffff";
    chartOptions.title = aaTitle;
    chartOptions.plotOptions = aaPlotOptions;
    chartOptions.series = aaSeries;
    chartOptions.colors = aaColors;
    chartOptions.legend = legend;
    
    return chartOptions;
}

#pragma mark -- AAChartView delegate
- (void)AAChartViewDidFinishLoad {
    NSLog(@"AChartView content did finish load!!!");
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)switchBtnClick:(UIButton *)sender{
    UIImage *img=[UIImage imageNamed:@"shouqi_shang"];
    UIImage *tinted = [img rt_tintedImageWithColor:lanse];
    [self.topTitleView.switchBtn setImage:tinted forState:UIControlStateNormal];
    [self.topTitleView.switchBtn setImage:tinted forState:UIControlStateHighlighted];
    bottomView = [[ManagerSheetView alloc] init];
    if (isSelected == YES) {
        bottomView.clickBtn1.selected = YES;
        bottomView.clickBtn2.selected = NO;
    } else{
        bottomView.clickBtn2.selected = YES;
        bottomView.clickBtn1.selected = NO;
    }
    bottomView.delegate = self;
    [bottomView show];
}



#pragma mark -
#pragma mark ManagerSheetViewDelegate
- (void)optionBtnClick:(UIButton *)sender{
    UIImage *img=[UIImage imageNamed:@"zhankai"];
    UIImage *tinted = [img rt_tintedImageWithColor:lanse];
    [self.topTitleView.switchBtn setImage:tinted forState:UIControlStateNormal];
    [self.topTitleView.switchBtn setImage:tinted forState:UIControlStateHighlighted];
    
    orderField = @"amount";
    _orderSort = @"desc";
    
    if (sender.tag == 0) {
        self.topTitleView.tongjiTypeLabel.text = @"统计表";
        isSelected = YES;
        bottomView.clickBtn1.selected = YES;
        bottomView.clickBtn2.selected = NO;
        [self addTable];
        pageSize = @"20";
        [self requestData];
        
    } else if (sender.tag == 1){
        self.topTitleView.tongjiTypeLabel.text = @"统计图";
        isSelected = NO;
        bottomView.clickBtn2.selected = YES;
        bottomView.clickBtn1.selected = NO;
        [self addChartTable];
        pageSize = @"50";
        [self requestData];
        
    } else{
//        NSLog(@"取消");
    }
    
    
 
}

@end
